package com.novunda.platform.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.novunda.platform.common.exception.ValidationErrorException;
import com.novunda.platform.common.utils.StringUtil;
import com.novunda.platform.common.web.controller.BaseController;
import com.novunda.platform.entities.Menu;
import com.novunda.platform.entities.Office;
import com.novunda.platform.services.MenuService;
import com.novunda.platform.services.OfficeService;
import com.novunda.platform.web.model.ResultModel;
import com.novunda.platform.web.model.SystemFunctionModel;
import com.novunda.platform.web.model.SystemReportModel;

/**
 * . 功能说明：权限上报接口
 * 
 * @author FJ
 * @see 2016年9月21日
 * @version 1.0
 */
@Controller
@RequestMapping("/authority/report")
public class SystemReportController extends BaseController {

	@Autowired
	private MenuService menuService;

	@Autowired
	private OfficeService officeService;

	/**
	 * . 功能说明：权限上报
	 * 
	 * @param String 权限上报对象json字符串
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@ResponseBody
	@RequestMapping(value = "authorityReport", produces = "application/json;charset=utf-8")
	public ResultModel authorityReport(String paramsJson) {
		ResultModel model = new ResultModel();
		Gson gson = new Gson();
		try {
			SystemReportModel systemReportModel = gson.fromJson(paramsJson, SystemReportModel.class);
			// 验证参数
			validateParams(systemReportModel);

			// 查询是否已有该机构的菜单
			String orgName = systemReportModel.getOrgName();
			Menu orgMenu = menuService.findByName(orgName);
			if (null == orgMenu) {
				// 如果没有新建一个，父菜单为系统初始化根机构
				Menu menu = new Menu();
				menu.setName(orgName);
				menu.setPermission(systemReportModel.getOrgPermission());
				menu.setParent(menuService.getMenu(1l));
				orgMenu = menuService.saveMenu(menu);
			}
			// 查询是否已有该系统的菜单
			String sysName = systemReportModel.getSysName();
			Menu sysMenu = menuService.findByName(sysName);
			if (null == sysMenu) {
				// 如果没有新建一个，父菜单为机构菜单
				Menu menu = new Menu();
				menu.setName(sysName);
				menu.setPermission(systemReportModel.getSysPermission());
				menu.setParent(orgMenu);
				sysMenu = menuService.saveMenu(menu);
			}

			// 系统功能菜单
			List<SystemFunctionModel> funcs = systemReportModel.getFuncs();
			for (int i = 0; i < funcs.size(); i++) {
				SystemFunctionModel funcModel = funcs.get(i);
				String funcName = funcModel.getFunctionName();
				String funcPermission = funcModel.getPermission();
				// 如果名字或者权限为空跳过
				if (StringUtil.isEmpty(funcName) || StringUtil.isEmpty(funcPermission)) {
					continue;
				}
				// 如果父功能为空，设置系统菜单为父菜单
				Menu parentMenu = null;
				if (null == funcModel.getParentFunc()) {
					parentMenu = sysMenu;
				} else {
					// 查询父菜单
					parentMenu = menuService.findByParentsIdAndNameAndPermission(sysMenu.getId(),
							funcModel.getParentFunc().getFunctionName(), funcModel.getParentFunc().getPermission());
				}
				// 查询自己是否已存在
				Menu funcMenu = menuService.findByParentsIdAndNameAndPermission(
						parentMenu == null ? sysMenu.getId() : parentMenu.getId(), funcName, funcPermission);
				// 如果不存在创建一个
				if (null == funcMenu) {
					funcMenu = new Menu();
				}
				funcMenu.setName(funcModel.getFunctionName());
				funcMenu.setPermission(funcModel.getPermission());
				funcMenu.setParent(parentMenu);
				// 保存
				menuService.saveMenu(funcMenu);
			}
			return model;
		} catch (JsonSyntaxException e) {
			LOG.error(e.getMessage(), e);
			model.setReturnCode(-2);
			model.setReturnMessage("json to object is fail， paramsJson: " + paramsJson + e.getMessage());
			return model;
		} catch (ValidationErrorException e) {
			model.setReturnCode(1);
			model.setReturnMessage(e.getMessage());
			return model;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			model.setReturnCode(-1);
			model.setReturnMessage("operation is inner exception: " + e.getMessage());
			return model;
		}

	}

	/**
	 * . 功能说明：验证参数
	 * 
	 * @param systemReportModel
	 * @throws ValidationErrorException
	 */
	private void validateParams(SystemReportModel systemReportModel) throws ValidationErrorException {
		if (null == systemReportModel) {
			throw new ValidationErrorException("权限上报model为空");
		}
		String orgName = systemReportModel.getOrgName();
		// 如果上报机构名为空，上报失败直接返回
		if (StringUtil.isEmpty(orgName)) {
			throw new ValidationErrorException("机构名为空");
		}

		String sysName = systemReportModel.getSysName();
		// 如果上报系统为空，上报失败直接返回
		if (StringUtil.isEmpty(sysName)) {
			throw new ValidationErrorException("系统名为空");
		}

		List<SystemFunctionModel> funcs = systemReportModel.getFuncs();
		// 如果上报集合为空，上报失败直接返回
		if (null == funcs || funcs.isEmpty()) {
			throw new ValidationErrorException("上报权限集合为空");
		}

		// 根据上报的名字查询机构，如果该机构不存在，上报失败直接返回
		Office org = officeService.getOfficeByName(orgName);
		if (null == org) {
			throw new ValidationErrorException("上报权限失败，不存在该机构：" + orgName);
		}
	}

}
